﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.Collections;
using ESRI.ArcGIS.Analyst3D;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.esriSystem;
using PlanningGIS.Framework;
using PlanningGIS.ArcGIS;
using PlanningGIS.Win.Controls;

namespace PlanningGIS.Analysis
{
    public partial class FrmDemArea : Office2007Form
    {
        private static FrmDemArea DefaultForm = null;
        private IApplication m_Application = null;
        private IFeatureClass pFeatureclass;
        private string evalue;

        public FrmDemArea()
        {
            InitializeComponent();
        }

        public IApplication Application
        {
            set
            {
                m_Application = value;
            }
        }

        public static FrmDemArea CreateNewForm()
        {
            if (DefaultForm == null || DefaultForm.IsDisposed)
            {
                DefaultForm = new FrmDemArea();
            }
            return DefaultForm;
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
        }

        private void FrmDemArea_Load(object sender, EventArgs e)
        {
            InitialForm();
        }

        private void InitialForm()
        {
            IMap pMap = (m_Application.Document as IMxDocument).ActiveView.FocusMap;
            List<IRasterLayer> pLyrnameArray = MapHelper.GetAllLayer<IRasterLayer>(pMap);

            foreach (IRasterLayer pRasterLyer in pLyrnameArray)
            {
                if ((pRasterLyer != null) && (pRasterLyer.Valid))
                {
                    CmbRasterLayer.Items.Add(pRasterLyer.Name);
                }
            }

            for (int i = 1; i <= 31; i++)
            {
                cmbClassify.Items.Add(i + 1);
            }

            cmbClassify.SelectedIndex = 1;

            if (CmbRasterLayer.Items.Count > 0)
            {
                CmbRasterLayer.SelectedIndex = 0;
            }

            pgbCalculate.Visible = false;
        }

        private void InitialdGdViewArea()
        {
            if ((CmbRasterLayer.Text.Length < 1) || (cmbClassify.Text.Length < 1)) return;

            IMap pMap = (m_Application.Document as IMxDocument).ActiveView.FocusMap;
            IRasterLayer pLyr = FindRasterLayerByName(pMap, CmbRasterLayer.Text);
            IRasterClassifyColorRampRenderer pRasterClassifyColorRampRenderer;
            IRasterRenderer pRasterRender;

            IRaster pRaster = pLyr.Raster;
            pRasterClassifyColorRampRenderer = new RasterClassifyColorRampRenderer();
            pRasterRender = pRasterClassifyColorRampRenderer as IRasterRenderer;
            pRasterRender.Raster = pRaster;
            pRasterRender.Update();

            int iNum;
            try
            {
                iNum = int.Parse(cmbClassify.Text);
            }
            catch
            {
                return;
            }

            pRasterClassifyColorRampRenderer.ClassCount = iNum;
            pRasterRender.Update();

            dGdViewArea.Rows.Clear();
            dGdViewArea.Rows.Add(iNum);

            for (int i = 0; i < iNum; i++)
            {
                dGdViewArea.Rows[i].Cells[0].Value = i + 1;
                dGdViewArea.Rows[i].Cells[0].ReadOnly = true;
                double low = pRasterClassifyColorRampRenderer.get_Break(i);
                double hight = pRasterClassifyColorRampRenderer.get_Break(i + 1);
                dGdViewArea.Rows[i].Cells[1].Value = low.ToString("F") + "~" + hight.ToString("F");
                dGdViewArea.Rows[i].Cells[2].Value = "";
                dGdViewArea.Rows[i].Cells[3].Value = "";
                dGdViewArea.Rows[i].Cells[2].ReadOnly = true;
                dGdViewArea.Rows[i].Cells[3].ReadOnly = true;
            }
        }

        private void labelX1_Click(object sender, EventArgs e)
        {

        }

        private void CmbRasterLayer_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitialdGdViewArea();
        }

        public static IRasterLayer FindRasterLayerByName(IMap pMap, string strName)
        {
            if (strName == null || strName == "") return null;

            List<IRasterLayer> LyrCol = MapHelper.GetAllLayer<IRasterLayer>(pMap);

            foreach (IRasterLayer lyr in LyrCol)
            {
                if (lyr.Valid)
                {
                    string layerName = lyr.Name;

                    //如果DEM图层是来者SDE中RasterCatalog，比如是SDE.DEM\Raster.OBJECTID=6 SDE.DEM\Raster.OBJECTID=2 获取简称后可能会出现重名，所以修改 张利勇
                    //layerName = CartoUtility.GetSimpleLayerName(layerName);
                    //strName = CartoUtility.GetSimpleLayerName(strName);
                    if (layerName.ToUpper() == strName.ToUpper())
                    {
                        return lyr;
                    }
                }
            }
            return null;
        }

        private void btnok_Click(object sender, EventArgs e)
        {
            IMap pMap = (m_Application.Document as IMxDocument).ActiveView.FocusMap;
            IRasterLayer pLyr = FindRasterLayerByName(pMap, CmbRasterLayer.Text);
            ISurface RSurface;

            RSurface = GetSurface(pLyr);

            pgbCalculate.Maximum = dGdViewArea.RowCount * 2;
            btnCsReport.Enabled = false;
            btncancel.Enabled = false;
            pgbCalculate.Visible = true;
            pgbCalculate.Value = 0;

            for (int i = 0; i <= dGdViewArea.RowCount - 1; i++)
            {
                System.Windows.Forms.Application.DoEvents();

                double low = 0;
                double hight = 0;

                string cellvalue = (string)dGdViewArea.Rows[i].Cells[1].Value;
                ConvetData(cellvalue, ref low, ref hight);
                double PrjArea = RSurface.GetProjectedArea(low, esriPlaneReferenceType.esriPlaneReferenceAbove) - RSurface.GetProjectedArea(hight, esriPlaneReferenceType.esriPlaneReferenceAbove);
                dGdViewArea.Rows[i].Cells[2].Value = PrjArea.ToString("F");
                pgbCalculate.Value = i * 2 + 1;
                Double SurArea = RSurface.GetSurfaceArea(low, esriPlaneReferenceType.esriPlaneReferenceAbove) - RSurface.GetSurfaceArea(hight, esriPlaneReferenceType.esriPlaneReferenceAbove);
                pgbCalculate.Value = i * 2 + 2;
                dGdViewArea.Rows[i].Cells[3].Value = SurArea.ToString("F");
            }

            pgbCalculate.Visible = false;
            pgbCalculate.Value = 0;
            btnCsReport.Enabled = true;
            btncancel.Enabled = true;
        }

        private static DataTable GetDatatableByStatic()
        {
            DataTable pTable = new DataTable();
            DataColumn pColumn = new DataColumn("高程分级组别");
            pColumn.DataType = Type.GetType("System.String");
            pTable.Columns.Add(pColumn);

            pColumn = new DataColumn("投影面积");
            pColumn.DataType = Type.GetType("System.Double");
            pTable.Columns.Add(pColumn);

            pColumn = new DataColumn("体表面积");
            pColumn.DataType = Type.GetType("System.Double");
            pTable.Columns.Add(pColumn);

            return pTable;
        }

        private ISurface GetSurface(IRasterLayer pRasterLayer)
        {
            IRasterSurface RasterSurface;
            ISurface RSurface;
            I3DProperties p3DProp;
            ILayerExtensions ple;
            IRasterBandCollection pBands;
            ple = pRasterLayer as ILayerExtensions;
            for (int k = 0; k <= ple.ExtensionCount - 1; k++)
            {
                if (ple.get_Extension(k) is I3DProperties)
                {

                    p3DProp = ple.get_Extension(k) as I3DProperties;
                    RasterSurface = (IRasterSurface)p3DProp.BaseSurface;
                    RSurface = RasterSurface as ISurface;
                    return RSurface;
                }
            }

            if (pRasterLayer.Raster != null)
            {
                RasterSurface = new RasterSurface();
                pBands = (IRasterBandCollection)pRasterLayer.Raster;
                RasterSurface.RasterBand = pBands.Item(0);
                RSurface = RasterSurface as ISurface;
                return RSurface;
            }
            else
            {
                return null;
            }
        }

        private void btncancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void cmbClassify_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitialdGdViewArea();
        }

        private void dGdViewArea_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1 && e.RowIndex >= 0)
            {
                try
                {
                    CheckData(1, e.RowIndex);
                }
                catch (Exception ex)
                {
                }
            }
        }

        private void CheckData(int col, int row)
        {
            int mark;
            double low;
            double high;

            string cellValue = (string)dGdViewArea.Rows[row].Cells[col].Value;
            if ((cellValue != null) && cellValue.Contains("~"))
            {
                if (cellValue.IndexOf("~") == cellValue.LastIndexOf("~"))
                {
                    mark = cellValue.IndexOf("~");
                    try
                    {
                        low = double.Parse(cellValue.Substring(0, mark));
                        high = double.Parse(cellValue.Substring(mark + 1));

                        if (high <= low)
                        {
                            MsgHelper.ShowInfomationMsgbox("~符号左边值应小于右边值，如：11.511~567.235！");
                            dGdViewArea.Rows[row].Cells[col].Value = evalue;
                        }
                        else
                        {
                            dGdViewArea.Rows[row].Cells[col + 1].Value = "";
                            dGdViewArea.Rows[row].Cells[col + 2].Value = "";
                        }
                    }
                    catch
                    {
                        MsgHelper.ShowInfomationMsgbox("请输入数值,并更正为形如：11.511~567.235！");
                        dGdViewArea.Rows[row].Cells[col].Value = evalue;
                        return;
                    }
                }
                else
                {
                    MsgHelper.ShowInfomationMsgbox("数据格式错误，请更正为形如：11.511~567.235 ");
                    dGdViewArea.Rows[row].Cells[col].Value = evalue;
                }
            }
            else
            {
                MsgHelper.ShowInfomationMsgbox("数据格式错误，请更正为形如：11.11~567.23 ");
                dGdViewArea.Rows[row].Cells[col].Value = evalue;
            }
        }

        private void ConvetData(string cellvalue, ref double low, ref double hight)
        {
            int mark = cellvalue.IndexOf("~");
            try
            {
                low = double.Parse(cellvalue.Substring(0, mark));
                hight = double.Parse(cellvalue.Substring(mark + 1));
            }
            catch
            {
                return;
            }
        }

        private void dGdViewArea_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            evalue = (string)dGdViewArea.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
        }

        private void btnCsReport_Click(object sender, EventArgs e)
        {
            DataTable pTable = new DataTable();
            pTable = GetDatatableByStatic();
            string PrjArea;
            string SurArea;
            string cellvalue;

            for (int i = 0; i <= dGdViewArea.RowCount - 1; i++)
            {
                DataRow pRow = pTable.NewRow();

                cellvalue = (string)dGdViewArea.Rows[i].Cells[1].Value;
                PrjArea = (string)dGdViewArea.Rows[i].Cells[2].Value;
                SurArea = (string)dGdViewArea.Rows[i].Cells[3].Value;
                if (PrjArea == "" || SurArea == "")
                {
                    MsgHelper.ShowInfomationMsgbox("请对数据进行分析计算后再生成报表。");
                    return;
                }
                pRow[0] = cellvalue;
                pRow[1] = Convert.ToDouble(PrjArea);
                pRow[2] = Convert.ToDouble(SurArea);
                pTable.Rows.Add(pRow);
            }

            //StatisticReport pReport = new StatisticReport();
            //pReport.AddConnectDatatable = pTable;
            //pReport.ReportName = "DEM高程分级统计.rpt";
            //pReport.ShowDialog();
        }
    }
}
